/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.entity.ShopCategory;
import com.rzico.basics.model.ShopExtVo;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.basics.service.ShopCategoryService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysOffice;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysEmployeeService;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysOfficeService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.AreaUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺/仓库控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "店铺/仓库接口")
@RestController
@RequestMapping("/admin/shop")
public class ShopAdminController extends BaseController {

    @Autowired
    private ShopService shopService;
    @Autowired
    protected ShopCategoryService shopCategoryService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private SysOfficeService sysOfficeService;


    @Autowired
    private SysEmployeeService sysEmployeeService;

    /**
     * 分页查询店铺/仓库
     *
     * @return
    */
    @ApiOperation("分页查询店铺/仓库")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "仓库名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "areaId", value = "城市", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型{0:店铺,1:提货点,2:仓库}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "scopeType", value = "经营范围 {0:其他,1:餐饮,2:酒店,3:名厨,4.餐车}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "receiverId", value = "收货地址", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "supplierId", value = "供应商Id", dataType = "Long", paramType = "query")
    })
    public CommResult<Shop> list(String name, Long areaId,Integer type,Long shopCategoryId,Integer scopeType, Pageable pageable, Long supplierId) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }

        if (areaId!=null){
            AreaUtils.encodeMap(areaId,params);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }


        //非管理员都启用数据权限
        SysUser sysUser = sysUserService.getCurrent();
        if (sysUser.getMchId().equals(enterprise.getMchId())) {
            if (!sysUserService.isAdmin(sysUser)) {
                params.put("shopScopeId", sysUser.getId());
            }
        }



        if (shopCategoryId!=null) {
            params.put("treePath",shopCategoryId);

        }

        if (type!=null) {
            params.put("type",type);
        }

        if (scopeType!=null) {
            params.put("scopeType",scopeType);
        }

        params.put("deleted",false);

        if (supplierId!=null) {
            params.put("supplierId",supplierId);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Shop> list = shopService.selectList(params);
        PageResult<Shop> pageResult = new PageResult<Shop>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条店铺/仓库
     *
     * @return
    */
    @ApiOperation("查询单条店铺/仓库")
    @GetMapping("/find/{id}")
    public CommResult<Shop> find(@PathVariable String id) {

        Shop result = shopService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("shop",result);

        if (result.getOfficeId()!=null) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            }
        }

        if (result.getManagerId()!=null) {
            SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(result.getManagerId());
            if (sysEmployee!=null) {
                data.put("managerName", sysEmployee.getName());
            }
        }

        return CommResult.success(data);

    }

    /**
     * 保存店铺/仓库
     *
     * @param shop
     * @return
     */
    @ApiOperation("保存店铺/仓库")
    @PostMapping("/save")
    public CommResult<Shop> save(@RequestBody Shop shop) {

        Enterprise enterprise = enterpriseService.getCurrent();
        shop.setEnterpriseId(enterprise.getId());
        shop.setDeleted(false);
        shop.setScore(0);
        shop.setMonthSale(0);
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        shop.setScopeType(sysMch.getScopeType());

        int affectCount = shopService.insertUseGeneratedKeys(shop);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Shop result = shopService.findById(shop.getId());
        return CommResult.success(result);

    }


    /**
     * 分页查询商户店铺
     *
     * @return
     */
    @ApiOperation("分页查询商户店铺")
    @GetMapping("/mchList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "仓库名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "status", value = "状态 {0:待审核,1:已审核,2.已关闭}", dataType = "Integer", paramType = "query") ,
            @ApiImplicitParam(name = "areaId", value = "城市", dataType = "Integer", paramType = "query") ,
            @ApiImplicitParam(name = "shopCategoryId", value = "分类ID", dataType = "Integer", paramType = "query") ,
            @ApiImplicitParam(name = "scopeType", value = "经营范围{0:其他,1:餐饮,2:酒店,3:名厨,4.餐车}", dataType = "Integer", paramType = "query")
    })
    public CommResult<Shop> mchList(String name,Integer status, Long areaId,Integer scopeType,Long shopCategoryId, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }

        if (areaId!=null){
            AreaUtils.encodeMap(areaId,params);
        }

        //非管理员都启用数据权限

        if (scopeType!=null) {
            params.put("scopeType",scopeType);
        }

        if (status!=null) {
            params.put("status",status);
        }

        if (shopCategoryId!=null) {
            params.put("treePath",shopCategoryId);

        }

        params.put("deleted",false);

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Shop> list = shopService.selectList(params);
        PageResult<Shop> pageResult = new PageResult<Shop>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条店铺/仓库
     *
     * @return
     */
    @ApiOperation("查询单条店铺/仓库")
    @GetMapping("/findMchShop")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "店铺ID", dataType = "String", paramType = "query") ,
    })
    public CommResult<ShopExtVo> findMchShop(String id) {
        Shop result = shopService.findById(id);

        ShopExtVo vo = new ShopExtVo();
        BeanUtils.copyProperties(result,vo);

        Enterprise enterprise = enterpriseService.selectByPrimaryKey(result.getEnterpriseId());
        vo.setBrokerage(enterprise.getBrokerage());
        vo.setPaybill(enterprise.getPaybill());
        vo.setBankId(enterprise.getBankId());
        vo.setBankName(enterprise.getBankName());
        vo.setBankNum(enterprise.getBankNum());
        vo.setBankType(enterprise.getBankType());

        vo.setFood(enterprise.getFood());
        vo.setThedoor(enterprise.getThedoor());
        vo.setScene(enterprise.getScene());
        vo.setLicense(enterprise.getLicense());
        vo.setIdCardBack(enterprise.getIdCardBack());
        vo.setIdCardFront(enterprise.getIdCardFront());
        vo.setMchId(enterprise.getMchId());
        vo.setLogo(enterprise.getLogo());
        vo.setBackground(enterprise.getBackground());
        vo.setShippingConfig(enterprise.getShippingConfig());
        vo.setNotice(enterprise.getNotice());

        vo.setPaused(enterprise.getPaused());

        if (vo.getShopCategoryId()!=null) {
            ShopCategory shopCategory = shopCategoryService.selectByPrimaryKey(vo.getShopCategoryId());
            if (shopCategory!=null) {
                vo.setShopCategoryName(shopCategory.getName());
            }
        }

        vo.setDeliverMethod(enterprise.getDeliverMethod());
        vo.setMinimumDelivery(enterprise.getMinimumDelivery());
        vo.setContent(enterprise.getContent());

        return CommResult.success(vo);

    }

    /**
     * 保存新商户
     *
     * @param shop
     * @return
     */
    @ApiOperation("保存新商户")
    @PostMapping("/saveMchShop")
    public CommResult<ShopExtVo> saveMchShop(@RequestBody ShopExtVo shop,Long[] tagIds,String username,String password) {

        Enterprise enterprise = enterpriseService.getCurrent();
        shop.setEnterpriseId(enterprise.getId());
        shop.setDeleted(false);

        shopService.saveMchShop(shop,username,password,tagIds);
        return CommResult.success(shop);

    }


    /**
     * 修改商户信息
     *
     * @param shop
     * @return
     */
    @ApiOperation("修改商户信息")
    @PostMapping("/updateMchShop")
    public CommResult<ShopExtVo> updateMchShop(@RequestBody ShopExtVo shop,Long[] tagIds) {

        shopService.updateMchShop(shop,tagIds);
        return CommResult.success(shop);

    }

    /**
     * 获取当前商户信息
     *
     * @return
     */
    @ApiOperation("获取当前商户信息")
    @PostMapping("/getInfo")
    public CommResult<ShopExtVo> getInfo() {

        Enterprise enterprise = enterpriseService.getCurrent();

        Shop shop = shopService.findByPoint(enterprise,0d,0d);

        ShopExtVo vo = new ShopExtVo();
        BeanUtils.copyProperties(shop,vo);

        vo.setBrokerage(enterprise.getBrokerage());
        vo.setPaybill(enterprise.getPaybill());
        vo.setBankId(enterprise.getBankId());
        vo.setBankName(enterprise.getBankName());
        vo.setBankNum(enterprise.getBankNum());
        vo.setBankType(enterprise.getBankType());

        vo.setFood(enterprise.getFood());
        vo.setThedoor(enterprise.getThedoor());
        vo.setScene(enterprise.getScene());
        vo.setLicense(enterprise.getLicense());
        vo.setIdCardBack(enterprise.getIdCardBack());
        vo.setIdCardFront(enterprise.getIdCardFront());
        vo.setMchId(enterprise.getMchId());
        vo.setLogo(enterprise.getLogo());
        vo.setBackground(enterprise.getBackground());
        vo.setPaused(enterprise.getPaused());
        vo.setNotice(enterprise.getNotice());

        if (vo.getShopCategoryId()!=null) {
            ShopCategory shopCategory = shopCategoryService.selectByPrimaryKey(vo.getShopCategoryId());
            if (shopCategory!=null) {
                vo.setShopCategoryName(shopCategory.getName());
            }
        }

        vo.setDeliverMethod(enterprise.getDeliverMethod());
        vo.setMinimumDelivery(enterprise.getMinimumDelivery());
        vo.setContent(enterprise.getContent());
        vo.setShippingConfig(enterprise.getShippingConfig());
        vo.setShippingMethod(enterprise.getShippingMethod());

        return CommResult.success(vo);

    }

    /**
     * 审核商户信息
     *
     * @param shop
     * @return
     */
    @ApiOperation("审核商户信息")
    @PostMapping("/auditMchShop")
    public CommResult<ShopExtVo> auditMchShop(@RequestBody ShopExtVo shop) {

        Enterprise enterprise = enterpriseService.getCurrent();
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (!sysMch.getMchType().equals(0)) {
            return CommResult.error("没有审核权限");
        }

        shopService.auditMchShop(shop);
        return CommResult.success(shop);

    }


    /**
     * 关闭及拒绝商户信息
     *
     * @param shop
     * @return
     */
    @ApiOperation("关闭及拒绝商户信息")
    @PostMapping("/closeMchShop")
    public CommResult<ShopExtVo> closeMchShop(@RequestBody ShopExtVo shop) {

        Enterprise enterprise = enterpriseService.getCurrent();
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (!sysMch.getMchType().equals(0)) {
            return CommResult.error("没有审核权限");
        }

        shopService.closeMchShop(shop);
        return CommResult.success(shop);

    }

    /**
     * 批量删除店铺/仓库
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除店铺/仓库", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除店铺/仓库,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Shop> del(@PathVariable String ids) {

        shopService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新店铺/仓库
     *
     * @param shop
     * @return
     */
    @Log(desc = "更新店铺/仓库", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新店铺/仓库")
    @PostMapping("/update")
    public CommResult<Shop> update(@RequestBody Shop shop) {
        int affectCount = shopService.updateByPrimaryKeySelective(shop);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Shop result = shopService.findById(shop.getId());
        return CommResult.success(result);
    }

}
